package modelLayer;

import java.io.IOException;
import java.util.ArrayList;

import controllerLayer.CustomerCtr;
import controllerLayer.EmployeeCtr;

import uiLayer.OfficeUI;
import uiLayer.SaveToFile;


public class LoanRecords {
	private ArrayList<Loan> loans; 
	private static LoanRecords instance = null; 
	public LoanRecords(){
		loans = new ArrayList<Loan>();
	}
	public static LoanRecords getInstance()       
    {
    	if(instance == null)
    	{
    		instance = new LoanRecords();
    	}
    	return instance;
    }
	public ArrayList<Loan> getLoans() {
		return loans;
	}
	

	public void loanProduct(String idCust, int idProd, String idEmp, String borrowDate, int period ){
		CustomerCtr cctr = new CustomerCtr();
		Customer c1 = cctr.getCustomer(idCust);
		EmployeeCtr ectr = new EmployeeCtr();
		Employee e1 = ectr .getEmployee(idEmp);
		ProductForLease p1 = LeaseProductsRecords.getInstance().getProduct(idProd);
		double total = p1.getPrice() * period;
		if(!p1.getState().equals("loaned")){
			try{
			Loan l1 = new Loan(borrowDate,period,c1,p1,e1);	
			loans.add(l1);
			p1.setQuantity(p1.getQuantity()-1);
			if(p1.getQuantity()==0)p1.setState("loaned");
			e1.setMoneyEarned(e1.getMoneyEarned()+total);
			c1.setMoneySpent(c1.getMoneySpent()+total);
			}
			catch(NullPointerException npe){
				System.out.println("Either customer, employee or product doesn't exist");
				OfficeUI.getInstance().run();
		}
		}
			else System.out.println("Product is not available");
					
		
		}
	
	public void returnProduct(int idProd)
	{
		ProductForLease p1 = LeaseProductsRecords.getInstance().getProduct(idProd);
		p1.setQuantity(p1.getQuantity()+1);
		p1.setState("available");
		
	}
	public void save() throws IOException{
		for(Loan l1: loans){
			SaveToFile.getInstance().save(l1.save());
		}
	}
	
}
